<template>
  <div class="category-select">
    <el-tree-select
      v-model="internalValue"
      :data="categoryList"
      :props="defaultProps"
      :multiple="multiple"
      :show-checkbox="multiple"
      class="w-1/1"
      node-key="id"
      placeholder="请选择商品分类"
      @change="handleChange"
    />
  </div>
</template>
<script lang="ts" setup>
import { defaultProps, handleTree } from '@/utils/tree'
import * as ProductCategoryApi from '@/api/mall/product/category'
import { oneOfType } from 'vue-types'
import { propTypes } from '@/utils/propTypes'

/** 商品分类选择组件 */
defineOptions({ name: 'ProductCategorySelect' })

const props = defineProps({
  // 选中的ID
  modelValue: oneOfType<number | number[]>([Number, Array<Number>]),
  // 是否多选
  multiple: propTypes.bool.def(false),
  // 上级品类的编号
  parentId: propTypes.number.def(undefined)
})

/** 分类选择 */
const emit = defineEmits(['update:modelValue'])

// 内部维护的选择顺序
const selectedOrder = ref<number[]>([])

// 内部值，用于与 el-tree-select 交互
const internalValue = computed({
  get: () => {
    return props.multiple ? selectedOrder.value : props.modelValue
  },
  set: (val: number | number[]) => {
    if (props.multiple && Array.isArray(val)) {
      // 找出新增的ID
      const newIds = val.filter(id => !selectedOrder.value.includes(id))
      // 找出移除的ID
      const removedIds = selectedOrder.value.filter(id => !val.includes(id))
      
      // 更新选择顺序
      selectedOrder.value = selectedOrder.value
        .filter(id => !removedIds.includes(id))
        .concat(newIds)
      
      emit('update:modelValue', selectedOrder.value)
    } else {
      emit('update:modelValue', val)
    }
  }
})

// 处理选择变化
const handleChange = (value: number | number[]) => {
  if (props.multiple && Array.isArray(value)) {
    internalValue.value = value
  }
}

/** 初始化 **/
const categoryList = ref<ProductCategoryApi.CategoryVO[]>([]) // 分类树
onMounted(async () => {
  // 获得分类树
  const data = await ProductCategoryApi.getCategoryList({ parentId: props.parentId })
  categoryList.value = handleTree(data, 'id', 'parentId')
  
  // 初始化选择顺序
  if (props.multiple && Array.isArray(props.modelValue)) {
    selectedOrder.value = [...props.modelValue]
  }
})
</script>

<style scoped>
.category-select {
  width: 100%;
}
</style>
